<template>
  <div class="app-container">

    <!-- 搜索表单 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-form-item>
            <el-input v-model="searchObj.keyword" clearable placeholder="关键字" />
        </el-form-item>
        <el-select v-model="searchObj.gender" clearable placeholder="性别">
          <el-option label="男生" value="1"></el-option>
          <el-option label="女生" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchObj.classId" filterable clearable placeholder="班级">
            <el-option
                v-for="item in classMapping"
                :key="item.classId"
                :label="item.className"
                :value="item.classId">
            </el-option>
        </el-select>
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="getList()">查询</el-button>
      <el-button type="success" icon="el-icon-plus" @click="addNewStudent">新增</el-button>
      <el-button :loading="downloadLoading" type="info" icon="el-icon-download" @click="handleModule">模版下载</el-button>
      <el-button :loading="downloadLoading" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
      <el-upload
            class="filter-item"
            ref="upload"
            accept=".xls,.xlsx"
            action="http://82.157.231.88:9200/api/student/uploadStudents"
            :before-upload="beforeUpload"
            name="uploadFile"
            :on-change="fileChange">
            <el-button icon="el-icon-upload" type="warning">导入</el-button>
        </el-upload>
    </el-form>

    <!-- 展示表格 -->
    <el-table :data="tableData" border stripestyle="width:100%">
      <el-table-column prop="studentName" label="姓名" align="center"/>
      <el-table-column prop="studentNum" label="学号" align="center"/>
      <el-table-column prop="gender" label="性别" align="center"/>
      <el-table-column prop="grade" label="年级" align="center"/>
      <el-table-column prop="className" label="班级" align="center"/>
      <el-table-column prop="schoolName" label="学校" align="center"/>
      <el-table-column prop="parentPhoneNum" label="家长联系" align="center"/>
      <el-table-column label="操作" width="280" align="center">
       <template slot-scope="scope">
           <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)" >编辑</el-button>
         <el-button type="danger" style="margin-left:5px" size="mini" @click="handleDelete(scope.row.studentId)">删除</el-button>
       </template>
      </el-table-column>
    </el-table>

    <!-- 编辑表单 -->
    <el-dialog title="请编辑信息" :visible.sync="dialogFormVisible">
        <el-form :model="form">
            <el-form-item label="姓名"  :label-width="formLabelWidth">
                <el-input v-model="form.studentName"></el-input>
            </el-form-item>
            <el-form-item label="学号"  :label-width="formLabelWidth">
                <el-input v-model="form.studentNum" ></el-input>
            </el-form-item>
            <el-form-item label="性别"  :label-width="formLabelWidth">
                <el-select v-model="form.gender">
                  <el-option label="男生" value="1"></el-option>
                  <el-option label="女生" value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="班级" :label-width="formLabelWidth">
                <el-select v-model="form.classId" filterable clearable>
                    <el-option
                        v-for="item in classMapping"
                        :key="item.classId"
                        :label="item.className"
                        :value="item.classId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="家长联系"  :label-width="formLabelWidth">
                <el-input v-model="form.parentPhoneNum" ></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="handleCancel">取 消</el-button>
            <el-button type="primary" @click="handleSure">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 新增表单 -->
        <el-dialog title="请编辑信息" :visible.sync="addFormVisible">
            <el-form :model="addForm">
                <el-form-item label="学生姓名" :label-width="formLabelWidth">
                    <el-input v-model="addForm.studentName" placeholder="名字"></el-input>
                </el-form-item>
                <el-form-item label="学生学号" :label-width="formLabelWidth">
                    <el-input v-model="addForm.studentNum" placeholder="学号"></el-input>
                </el-form-item>
                <el-form-item label="性别"  :label-width="formLabelWidth">
                  <el-select v-model="addForm.gender">
                    <el-option label="男生" value="1"></el-option>
                    <el-option label="女生" value="0"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="班级" :label-width="formLabelWidth">
                  <el-select v-model="addForm.classId" filterable clearable>
                      <el-option
                          v-for="item in classMapping"
                          :key="item.classId"
                          :label="item.className"
                          :value="item.classId">
                      </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="家长联系" :label-width="formLabelWidth">
                    <el-input v-model="addForm.parentPhoneNum" placeholder="手机号"></el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleCancel">取 消</el-button>
                <el-button type="primary" @click="handleAddSure">确 定</el-button>
            </div>
        </el-dialog>

    <!-- 分页 -->
    <el-pagination
      background
      :current-page="page"
      :page-size="limit"
      :total="total"
      layout="prev, pager, next"
      style="padding: 30px 0; text-align: center;"
      @current-change="getList">
    </el-pagination>
  </div>
</template>

<script>
import { getStudentsByPage,
         addStudent,
         alterStudent,
         deleteStudent,
         getTemplate,
         getStudentExcel,
       } from '@/api/managementModule/student';
import { getClassInfo,getClassesByPage } from '@/api/managementModule/classManagement';
export default {
  data(){
    return {
      limit: 10,
      page: 1, //分页组件页码初始化
      searchObj: {}, // 条件搜索对象
      currentPage: 1, //当前页
      tableData:[],
      total: 20,
      classMapping:{},
      formLabelWidth: '120px',
      addFormVisible: false,
      addForm: {},
      downloadLoading: false, // 导出按钮
      dialogFormVisible: false, //编辑表单
      form: {}, //表单信息
      teacherID:'',
      username:''
    }
  },
  created(){
    //获取全部的班级信息
    getClassInfo().then(res => {
      this.classMapping = res.data.map( item => {
        return {
          classId: item.id,
          className: `${item.grade}${item.className}`
        }
      })
    })
    this.getClassID();
  },
  mounted() {
    this.getList();
  },
  methods: {
    //根据当前的教师ID，获取教师的班级ID
    getClassID(page = 1){
      var teacherID=JSON.parse(sessionStorage.getItem('userInfo')).id;
      var username=JSON.parse(sessionStorage.getItem('userInfo')).username;
      if(username == 'admin') return;
      if(teacherID==null){
      this.$message({
          type: 'error',
          message: '当前账户未登录!'
       });
       sessionStorage.clear;//清除sessionStorage
       this.$store.dispatch('user/resetToken') //非接口版本退出登录
       this.$router.push(`/login?redirect=${this.$route.fullPath}`) //跳转到登录页面
      }

      this.currentPage = page;
        const payload = {
        pageSize: 10,
        pageNum: this.currentPage,
        monitorId:this.teacherID //传入教师ID
      }
        //根据教师ID获取班级ID
        getClassesByPage(payload).then(res => {
        var classId=res.data.list[0].id;
        if(classId == null){
          this.$message({
          type: 'error',
          message: '班级数据获取异常!'
        });
        }else{
          sessionStorage.setItem("classId",JSON.stringify(res.data.list[0].id))
        }
      })
    },

    getList(page = 1){
      this.currentPage = page;
      console.log(this.currentPage)
      var classId=JSON.parse(sessionStorage.getItem('classId'))
      const payload = {
        pageSize: 10,
        pageNum: this.currentPage,
        classId:classId,//传入教师ID
        ...this.searchObj,
      }
      getStudentsByPage(payload).then(res => {
        this.total = res.data.total;
        this.tableData = res.data.list.map(item => {
          return {
            ...item,
            gender: item.gender == 0 ? '女' : '男',
          }
        })
      })
    },

    handleEdit(index, row){
        this.dialogFormVisible = true;
        this.form = row;
    },
    beforeUpload(file) {
        //文件类型
        const isType = file.type === 'application/vnd.ms-excel'
        const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        const fileType = isType || isTypeComputer
        if(!fileType) {
            this.$message.error('上传文件只能是xls/xlsx格式！')
        }

        // 文件大小限制为10M
        const fileLimit = file.size / 1024 / 1024 < 10;
        if(!fileLimit) {
            this.$message.error('上传文件大小不超过10M！')
        }
        return fileType && fileLimit
    },
    fileChange(file, fileList){
      console.log(file);
    },
    addNewStudent(){
      this.addFormVisible = true;
    },
    handleCancel(){
      this.dialogFormVisible = false;
      this.addFormVisible = false;
      this.getList();
    },
    handleModule(){
      getTemplate();
    },
    handleAddSure(){
      addStudent(this.addForm).then(res => {
        this.$message({
              message: '添加成功',
              type: 'success'
            });
          this.getList();
        })
      this.addFormVisible = false;
    },
    handleSure(){
      if(this.form.gender == '男'){
        this.form.gender = 1;
      }
      if(this.form.gender == '女'){
        this.form.gender = 0;
      }
      alterStudent(this.form).then(res => {
        this.$message({
            message: '修改成功',
            type: 'success'
          });
        this.getList();
      })
      this.dialogFormVisible = false;
    },
    //导出学生数据
    handleDownload() {
      this.downloadLoading = true;
      getStudentExcel(this.searchObj);
      this.downloadLoading = false;
    },
    handleDelete(studentId){
      deleteStudent({studentId}).then(res => {
        this.$message({
            message: '删除成功',
            type: 'success'
          });
        this.getList();
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.filter-item{
  float: right;
  margin-right: 40px;
}

</style>
